package com.centling.smartSealForPhone.activity;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;

import com.centling.smartSealForPhone.BuildConfig;
import com.centling.smartSealForPhone.R;
import com.centling.smartSealForPhone.adapter.RvBlueListAdapter;
import com.centling.smartSealForPhone.constants.GlobalData;
import com.centling.smartSealForPhone.constants.UrlConstants;
import com.wsdk.service.BluetoothLeService;
import com.centling.smartSealForPhone.utils.ControlUtil;
import com.centling.smartSealForPhone.utils.LogUtil;
import com.centling.smartSealForPhone.utils.OkHttpUtil;
import com.centling.smartSealForPhone.utils.ParseBluetoothData;
import com.centling.smartSealForPhone.utils.ShowDialog;
import com.centling.smartSealForPhone.utils.ShowToast;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author fionera
 */
public class RegisterActivity extends BaseActivity {

    private static final int OPEN_BLUE_DIALOG = 1;
    public int connPosition = -1;
    public int successPosition = -1;
    private BluetoothAdapter bluetoothAdapter;
    private List<BluetoothDevice> devices = new ArrayList<>();
    private boolean isScanning = false;
    private RecyclerView recyclerView;
    private String mSN;
    private BluetoothAdapter.LeScanCallback leScanCallback = new BluetoothAdapter.LeScanCallback() {

        @Override
        public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
            LogUtil.d("Search Bluetooth Device:" + device.getName() + " " + device.getAddress());
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    addDeviceToList(device);
                }
            });
        }
    };

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
                successPosition = -1;
                connPosition = -1;
                recyclerView.getAdapter().notifyDataSetChanged();
                startSearchBlueDevice();
            } else if (BluetoothLeService.ACTION_GATT_HARDWARE_CONNECTED.equals(action)) {
                syncTimeV1();
            } else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
                mProcessDialog.dismiss();
                if (BuildConfig.DEBUG) {
                    ShowToast.shortTime("Reg List Connected");
                }
                GlobalData.isConnect = true;
                new ControlUtil().getSN();
            } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
                byte[] data = intent.getByteArrayExtra(BluetoothLeService.EXTRA_DATA);

                if (ParseBluetoothData.isSycTime(data)) {
                    if (ParseBluetoothData.parseSyncTime(data)) {
                        GlobalData.selfCheckStatus = "0";
                        sendBroadcast(new Intent(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED));
                    } else {
                        BluetoothLeService.disconnect();
                    }
                } else if (ParseBluetoothData.isGetSN(data)) {
                    mSN = ParseBluetoothData.parseSN(data);
                    connPosition = -1;
                    successPosition = connPosition;

                    Map<String, String> param = new HashMap<>();
                    param.put("equipSn", mSN);
                    postJsonEnqueue(UrlConstants.CHECK_SN, param, new OkHttpUtil.NetCallBack() {
                        @Override
                        public void onSucceed(String json) {
                            String res = "";
                            try {
                                res = new JSONObject(json).optString("isRegistable");
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            switch (res) {
                                case "1":
                                    ShowDialog.showSelectDialog(mContext, "提示信息", "设备可注册，是否点击注册", "",
                                            new View.OnClickListener() {
                                                @Override
                                                public void onClick(View v) {
                                                    Intent intent = new Intent(RegisterActivity.this, RegisterSubmitActivity.class);
                                                    intent.putExtra("SN", mSN);
                                                    startActivity(intent);
                                                    finish();
                                                }
                                            }, new View.OnClickListener() {
                                                @Override
                                                public void onClick(View v) {
                                                    BluetoothLeService.disconnect();
                                                    successPosition = -1;
                                                    connPosition = -1;
                                                    recyclerView.getAdapter().notifyDataSetChanged();
                                                }
                                            });
                                    break;
                                case "2":
                                    ShowToast.shortTime("设备未报备");
                                    BluetoothLeService.disconnect();
                                    successPosition = -1;
                                    connPosition = -1;
                                    recyclerView.getAdapter().notifyDataSetChanged();
                                    break;
                                default:
                                    ShowToast.shortTime("该设备已注册");
                                    BluetoothLeService.disconnect();
                                    successPosition = -1;
                                    connPosition = -1;
                                    recyclerView.getAdapter().notifyDataSetChanged();
                                    break;
                            }
                        }

                        @Override
                        public void onFailed(String reason) {
                            ShowToast.shortTime(reason);
                            BluetoothLeService.disconnect();
                            successPosition = -1;
                            connPosition = -1;
                            recyclerView.getAdapter().notifyDataSetChanged();
                        }
                    });
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_regidter);
//        setTitleBarText("云注册 ");

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_HARDWARE_CONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
        registerReceiver(mBroadcastReceiver, intentFilter);

        recyclerView = findViewById(R.id.register_bluetooth_list);

        initData();

        checkBTAvailable();

        startSearchBlueDevice();
    }

    private void initData() {

        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayout.VERTICAL, false));
        RvBlueListAdapter listAdapter = new RvBlueListAdapter(this, devices);
        listAdapter.setOnItemClickListener(new RvBlueListAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int postion) {
                if (isScanning) {
                    stopSearch();
                }
                connPosition = postion;
                recyclerView.getAdapter().notifyDataSetChanged();
                connectDevice(devices.get(postion));
            }

        });
        recyclerView.setAdapter(listAdapter);
    }

    private void checkBTAvailable() {
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            ShowToast.shortTime("您的手机不支持蓝牙");
            finish();
            return;
        }
        BluetoothManager manager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        bluetoothAdapter = manager.getAdapter();
        if (bluetoothAdapter == null) {
            ShowToast.shortTime("设备不支持蓝牙");
            finish();
        }
    }

    private void startSearchBlueDevice() {
        isScanning = true;
        devices.clear();
        recyclerView.getAdapter().notifyDataSetChanged();
        bluetoothAdapter.startLeScan(leScanCallback);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!bluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, OPEN_BLUE_DIALOG);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        stopSearch();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BluetoothLeService.disconnect();
        unregisterReceiver(mBroadcastReceiver);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == OPEN_BLUE_DIALOG && resultCode == RESULT_CANCELED) {
            onBackPressed();
        } else if (requestCode == OPEN_BLUE_DIALOG && resultCode == RESULT_OK) {
            startSearchBlueDevice();
        }
    }

    private void connectDevice(BluetoothDevice connectDevice) {
        Intent intent = new Intent(this, BluetoothLeService.class);
        intent.putExtra("DEVICE_ADDRESS", connectDevice.getAddress());
        startService(intent);
    }

    private void stopSearch() {
        isScanning = false;
        bluetoothAdapter.stopLeScan(leScanCallback);
    }

    private long preNotifyTime = 0;
    private final static long NOTIFY_INTERVAL = 2000;

    private void addDeviceToList(BluetoothDevice device) {
        if (!devices.contains(device)) {
            if ("HMSoft".equals(device.getName())) {
                devices.add(device);
            }

            long curTime = System.currentTimeMillis();
            if (curTime - preNotifyTime > NOTIFY_INTERVAL) {
                preNotifyTime = curTime;
                recyclerView.getAdapter().notifyDataSetChanged();
            }
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        BluetoothLeService.disconnect();
        devices.clear();
        finish();
    }
}
